package com.esm.md11.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esm.md11.R;
import com.esm.md11.database.dbmodel.SystemAllInfo;
import com.esm.md11.database.manager.SystemCenter;
import com.esm.md11.util.Config;
import com.esm.md11.util.HttpRequest;
import com.esm.md11.util.NotificationUtils;
import com.esm.md11.util.Utils;

import java.util.ArrayList;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.BottomMenuWindow;
import zuo.biao.library.util.JSON;

public class LoginActivity extends BaseActivity implements View.OnClickListener, AlertDialog.OnDialogButtonClickListener {

    private final String TAG = "LoginActivity";

    public static Intent createIntent(Context context) {
        return new Intent(context, LoginActivity.class);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    private BroadcastReceiver mRegistrationBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);

        initView();
        initData();
        initEvent();
    }

    String _fcmtoken = "";

    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);
        Log.e(TAG, "Firebase reg id: " + regId);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    @Override
    public void onForwardClick(View v) {

    }

    private EditText edit_username;
    private EditText edit_mima;
    private TextView edit_group;


    @Override
    public void initView() {
        edit_username = (EditText) findViewById(R.id.edit_username);
        edit_mima = (EditText) findViewById(R.id.edit_mima);
        edit_group = (TextView) findViewById(R.id.edit_group);
    }

    @Override
    public void initData() {

        SystemAllInfo lastusername = SystemCenter.getInstance().getSysInfo("lastusername");
        if (lastusername != null) {
            _username = lastusername.getContent();
            edit_username.setText(_username);
            SystemAllInfo mima = SystemCenter.getInstance().getSysInfo(lastusername.getContent());
            if (mima != null) {
                _mima = mima.getContent();
                edit_mima.setText(_mima);
            }
        }

    }

    String _username = "";
    String _mima = "";

    @Override
    public void initEvent() {
        findViewById(R.id.tv_login).setOnClickListener(this);
        findViewById(R.id.edit_group).setOnClickListener(this);
    }

    String[] GROUP_NAMES = null;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.edit_group:
                break;
            case R.id.tv_login:
                onLogin();
                break;
        }
    }

    boolean _islogining = false;

    private void onLogin() {
        _username = edit_username.getText().toString();
        _mima = edit_mima.getText().toString();
        if (_username.isEmpty() || _mima.isEmpty()) {
            showShortToast("请输入用户名和密碼！");
            return;
        }

        if (_islogining) {
            return;
        }

        Utils.log("login token=" + _fcmtoken);

        showProgressDialog(R.string.loading);

        _islogining = true;

        try {
            HttpRequest.login(_username, _mima, _fcmtoken, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    _islogining = false;
                    dismissProgressDialog();
                    if (code == 1) {
                        JSONObject data = jsonObject == null ? null : jsonObject.getJSONObject("data");
//                        SystemCenter.getInstance().adminid = data.getInteger("id");
                        finishlogin();
                    } else {
                        showShortToast("登录失败！");
                    }
                }
            });
        } catch (Exception e1) {
            showShortToast("网络无链接！");
            _islogining = false;
            dismissProgressDialog();
        }
    }

    private void finishlogin() {
        SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "lastusername", _username));
        SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, _username, _mima));
        SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "zcgroup", edit_group.getText().toString()));
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.PUSH_NOTIFICATION));

        // clear the notification area when the app is opened
        NotificationUtils.clearNotifications(getApplicationContext());
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void zcgrouplist() {
        showProgressDialog(R.string.loading);

        try {
            HttpRequest.zcgrouplist(0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    dismissProgressDialog();
                    if (code == 1) {
                    }
                }
            });
        } catch (Exception e1) {
            showShortToast("網絡無連接！");
            dismissProgressDialog();
        }
    }

    private final int REQUEST_TO_BOTTOM_MENU_1 = 31;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_TO_BOTTOM_MENU_1:
                break;
        }
    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {

    }
}

